<template>
    <div class="edit-profile-container">
        <div class="header">
            <button class="back-btn" @click="goBack">
                <van-icon name="arrow-left" size="20" />
                <span>返回</span>
            </button>
            <h1>个人设置</h1>
            <button class="save-btn" @click="saveChanges">保存</button>
        </div>

        <div class="profile-form">
            <div class="form-section">
                <h2>基本信息</h2>

                <div class="avatar-upload">
                    <div class="avatar-preview">
                        <img :src="avatarUrl" alt="用户头像">
                    </div>
                    <button class="upload-btn" @click="uploadAvatar">更换头像</button>
                </div>

                <div class="form-item">
                    <label>姓名</label>
                    <input type="text" v-model="name" placeholder="请输入姓名">
                </div>

                <div class="form-item">
                    <label>学号</label>
                    <input type="text" v-model="studentId" placeholder="请输入学号" readonly>
                </div>

                <div class="form-item">
                    <label>专业班级</label>
                    <input type="text" v-model="className" placeholder="请输入专业班级">
                </div>

                <div class="form-item">
                    <label>邮箱地址</label>
                    <input type="email" v-model="email" placeholder="请输入邮箱地址">
                </div>
            </div>

            <div class="form-section">
                <h2>通知设置</h2>

                <div class="form-item checkbox-item">
                    <label>考试提醒</label>
                    <van-switch v-model="examReminder" />
                </div>

                <div class="form-item checkbox-item">
                    <label>作业提醒</label>
                    <van-switch v-model="homeworkReminder" />
                </div>

                <div class="form-item checkbox-item">
                    <label>系统通知</label>
                    <van-switch v-model="systemNotification" />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Toast } from 'vant';
import { updateUserInfo } from '../../api/userApi';

// 检查用户是否已登录
const checkLoginStatus = () => {
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    return !!(token && user);
};

export default {
    name: 'EditProfile',
    data() {
        return {
            // 响应式数据
            avatarUrl: 'https://picsum.photos/200/200',
            name: '',
            username: '',
            id: '',
            className: '',
            email: '',
            examReminder: true,
            homeworkReminder: true,
            systemNotification: true
        };
    },
    methods: {
        // 方法
        goBack() {
            this.$router.go(-1);
        },
        saveChanges() {
            // 验证表单数据
            if (!this.username) {
                Toast('用户名不能为空');
                return;
            }
            if (!this.role) {
                Toast('用户角色不能为空');
                return;
            }
            if (!this.name) {
                Toast('姓名不能为空');
                return;
            }
            if (this.email && !/^\S+@\S+\.\S+$/.test(this.email)) {
                Toast('请输入有效的邮箱地址');
                return;
            }
            // 收集要更新的数据
            const updateData = {
                username: this.username,
                name: this.name,
                email: this.email || undefined,
                role: this.role || 'student',
                classId: this.className ? parseInt(this.className.replace('软件工程', '').replace('班', '')) : undefined
            };

            // 移除值为undefined的字段
            Object.keys(updateData).forEach(key => {
                if (updateData[key] === undefined) {
                    delete updateData[key];
                }
            });


            // 调用更新用户信息接口
            updateUserInfo(this.id, updateData)
                .then(res => {
                    Toast('资料保存成功');
                    console.log('更新成功响应:', res);
                    // 更新localStorage中的用户数据
                    const user = JSON.parse(localStorage.getItem('user'));
                    localStorage.setItem('user', JSON.stringify({ ...user, ...res }));
                    this.$router.push('/profile');
                })
                .catch(error => {
                    console.error('更新用户信息失败:', error);
                    // 处理特定错误类型
                    if (error.response && error.response.status === 403) {
                        Toast('权限不足，无法更新用户信息');
                    } else if (error.response && error.response.status === 404) {
                        Toast('用户不存在');
                    } else if (error.response && error.response.status === 400) {
                        Toast('请求数据格式错误');
                    } else {
                        Toast('资料保存失败：' + (error.message || '未知错误'));
                    }
                });
        },
        uploadAvatar() {
            // 模拟上传头像
            Toast('上传头像功能待实现');
        }
    },

    mounted() {
        // 检查登录状态
        if (!checkLoginStatus()) {
            Toast('请先登录');
            this.$router.push('/login');
            return;
        }

        const user = JSON.parse(localStorage.getItem('user'))
        this.name = user.name;
        this.username = user.username || '';
        this.role = user.role || '';
        this.studentId = user.id || '';
        this.className = user.classId ? "软件工程" + user.classId + "班" : '';
        this.email = user.email || '';
        // 设置学习数据
        this.averageScore = user.averageScore || 0;
        this.examCount = user.examCount || 0;
        this.certificateCount = user.certificateCount || 0;
    }
};
</script>

<style scoped>
.edit-profile-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.back-btn,
.save-btn {
    display: flex;
    align-items: center;
    background: none;
    border: none;
    font-size: 16px;
    padding: 5px 10px;
    cursor: pointer;
}

.back-btn {
    color: #666;
}

.save-btn {
    color: #722ED1;
    font-weight: bold;
}

h1 {
    font-size: 20px;
    font-weight: bold;
    color: #333;
}

.profile-form {
    background-color: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.form-section {
    margin-bottom: 30px;
}

h2 {
    font-size: 16px;
    font-weight: bold;
    color: #722ED1;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.avatar-upload {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30px;
}

.avatar-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 15px;
    border: 2px solid #eee;
}

.avatar-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.upload-btn {
    background-color: #f5f5f5;
    border: 1px dashed #d9d9d9;
    color: #666;
    padding: 6px 20px;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
}

.form-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
}

label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
}

input {
    padding: 10px 15px;
    border: 1px solid #d9d9d9;
    border-radius: 8px;
    font-size: 14px;
    outline: none;
}

input:focus {
    border-color: #722ED1;
}

.checkbox-item {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}

.checkbox-item label {
    margin-bottom: 0;
}
</style>